﻿using System;
using System.IO;

namespace Borg.Framework
{
    public sealed class ResourceStreamGetter : IDisposable
    {
        private Stream _stream;

        public ResourceStreamGetter(RepositoryElement plugin, string name, bool useNamespace)
        {
            string str;

            if (plugin == null)
                throw new ArgumentNullException("plugin");

            if (name == null)
                throw new ArgumentNullException("name");

            var assembly = plugin.Assembly;

            if (useNamespace)
            {
                var fileNameWithoutExtension =
                    System.IO.Path.GetFileNameWithoutExtension(plugin.Name);

                str = string.Format("{0}.{1}", fileNameWithoutExtension, name);
            }
            else
                str = name;

            _stream = assembly.GetManifestResourceStream(str);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!disposing || _stream == null)
                return;

            _stream.Dispose();
            _stream = null;
        }

        ~ResourceStreamGetter()
        {
            Dispose(false);
        }

        public static ResourceStreamGetter GetResourceStream(PluginInfo plugin,
            string resourceName, bool useNamespace)
        {
            return new ResourceStreamGetter(plugin, resourceName, useNamespace);
        }

        public Stream Stream
        {
            get { return _stream; }
        }
    }
}

